package com.hxzy.controller.common;

import com.hxzy.common.core.domain.R;
import com.hxzy.common.utils.file.FileUploadUtils;
import com.hxzy.common.utils.file.MimeTypeUtils;
import com.hxzy.fileupload.service.IFileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Api(tags = "通用文件上传")
@RestController
@RequestMapping(value = "/api/upload")
public class FileUploadController {
    // 配置缩略图宽
    @Value(value = "${fdfs.thumb-image.width}")
    private String width;
    // 配置缩略图高
    @Value(value = "${fdfs.thumb-image.height}")
    private String height;


    /**
     * 指定使用fastdfs来上传
     */
    @Autowired
    private IFileUploadService  fastDfsFileUploadServiceImpl;


    @ApiOperation(value = "只支持图片(bmp, gif, jpg, jpeg, png)")
    @PostMapping(value = "/image")
    public R  imageUpload(@RequestPart(value = "file", required = true) MultipartFile file) throws Exception {

        // 判断是否是图片
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);

        String imageUrl = this.fastDfsFileUploadServiceImpl.uploadFile(file);

        //返回类型
        Map<String,Object> data=new HashMap<>();
        data.put("url",  imageUrl);
        data.put("fileName", file.getOriginalFilename());

        return R.okHasData(data);
    }


    @ApiOperation(value = "只支持图片(bmp, gif, jpg, jpeg, png)并生成缩略图")
    @PostMapping(value = "/image_thumb" )
    public R  uploadImageAndCrtThumbImage(@RequestPart(value = "file", required = true) MultipartFile file) throws Exception {

        // 判断是否是图片
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);

        String imageUrl = this.fastDfsFileUploadServiceImpl.uploadImageAndCrtThumbImage(file);

        //返回类型
        Map<String,Object> data=new HashMap<>();
        data.put("url",  imageUrl);

        //文件后缀名
        String ext=imageUrl.substring( imageUrl.lastIndexOf("."));
        //前缀名
        String prev=imageUrl.substring(0, imageUrl.lastIndexOf("."));

        //生成缩图名
        StringBuffer  sb=new StringBuffer();
        sb.append(prev);
        sb.append("_").append(width).append("x").append(height);
        sb.append(ext);

        data.put("thumburl",  sb.toString());
        data.put("fileName", file.getOriginalFilename());

        return R.okHasData(data);
    }


}
